import { Editor } from 'tinymce'

interface PluginConfig {
  name: string
  svg: string
  accept: string
  tooltip: string
  handler: (editor: Editor, file: File) => Promise<void>
}

export function createBasePlugin(config: PluginConfig) {
  return function (editor: Editor) {
    // 注册图标
    if (!editor.ui.registry.getAll().icons[config.name]) {
      editor.ui.registry.addIcon(config.name, config.svg)
    }

    // 注册按钮
    editor.ui.registry.addButton(config.name, {
      icon: config.name,
      tooltip: config.tooltip,
      onAction: () => {
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = config.accept

        input.onchange = async function () {
          const file = this.files?.[0]
          if (!file) return

          try {
            await config.handler(editor, file)
          } catch (err) {
            editor.notificationManager.open({
              text: '处理失败',
              type: 'error'
            })
          }
        }

        input.click()
      }
    })

    // 注册命令
    editor.addCommand(config.name, function () {
      editor.execCommand(config.name)
    })

    return {
      getMetadata: () => ({
        name: config.name,
        url: 'https://your-domain.com/plugins/' + config.name
      })
    }
  }
}

export function registerPlugin(name: string, plugin: (editor: Editor) => any) {
  const global = window.tinymce.util.Tools.resolve('tinymce.PluginManager')
  global.add(name, plugin)
}

